package com.autotau;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.*;
import android.widget.*;


public class AutoTau extends Activity
{
  /**
   * Called when the activity is first created.
   */
  @Override
  public void onCreate(Bundle savedInstanceState)
  {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    InitMain();
  }

  private void InitMain()
  {
    final EditText editUser = (EditText) findViewById(R.id.editTextUser);
    final EditText editPass = (EditText) findViewById(R.id.editTextPass);

    final SharedPreferences settings = getSharedPreferences(AutoTauService.PREFS_NAME, 0);
    final SharedPreferences.Editor editor = settings.edit();

    String user = settings.getString("username", "");
    String pass = settings.getString("password", "");
    editUser.setText(user);
    editPass.setText(pass);

    Button buttonStart = (Button) findViewById(R.id.buttonStart);
    buttonStart.setOnClickListener(new View.OnClickListener()
    {
      public void onClick(View v)
      {
        editor.putString("username", editUser.getText().toString());
        editor.putString("password", editPass.getText().toString());

        editor.commit();

        startService(new Intent(AutoTauService.ACTION_SERVICE));
      }
    });
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu)
  {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.layout.menu, menu);
    
    return true;
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item)
  {
    switch (item.getItemId())
    {
      case R.id.about:
        String version = "";
        PackageManager pm = getPackageManager();
        
        try
        {
          PackageInfo pi = pm.getPackageInfo("com.autotau", 0);
          version = pi.versionName;
        }
        catch (PackageManager.NameNotFoundException e)
        {
          e.printStackTrace();
        }

        Resources res = getResources();
        String title = res.getString(R.string.about_title);
        String message = String.format(res.getString(R.string.about_message), version);

        AlertDialog.Builder alert = new AlertDialog.Builder(this);
        alert.setTitle(title);
        alert.setMessage(message);
        alert.setPositiveButton("Ok", null);

        alert.show();
        break;
    }
    
    return true;
  }
}
